package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.config.PrivateConfig;
import com.cjack.frenchexcel.dao.ConsumerRecordDao;
import com.cjack.frenchexcel.dao.RechargeRecordDao;
import com.cjack.frenchexcel.dao.SendGoodsRecordDao;
import com.cjack.frenchexcel.dao.UserAdminDao;
import com.cjack.frenchexcel.model.UserSummaryModel;
import com.cjack.frenchexcel.table.AdminUserTable;
import com.cjack.frenchexcel.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据统计相关
 * Created by root on 10/5/19
 */
@Service
public class DataSummaryService {

    @Autowired
    private UserAdminDao userAdminDao;
    @Autowired
    private RechargeRecordDao rechargeRecordDao;
    @Autowired
    private ConsumerRecordDao consumerRecordDao;
    @Autowired
    private MooncardCardService mooncardCardService;
    @Autowired
    private SendGoodsRecordDao sendGoodsRecordDao;

    public static void main(String[] args) throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, null, null);

        SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket();

        String[] protocols = socket.getSupportedProtocols();

        System.out.println("Supported Protocols: " + protocols.length);
        for (int i = 0; i < protocols.length; i++) {
            System.out.println(" " + protocols[i]);
        }

        protocols = socket.getEnabledProtocols();

        System.out.println("Enabled Protocols: " + protocols.length);
        for (int i = 0; i < protocols.length; i++) {
            System.out.println(" " + protocols[i]);
        }
    }
    /**
     * 统计员工的 充值消费记录情况
     */
    public List<UserSummaryModel> employee( Long loginUserId){
        AdminUserTable loginUser = userAdminDao.getOne( loginUserId);
        List<AdminUserTable> users;
        //员工只能查看到自己的汇总数据
        if( loginUser.getRole().getCode().equals( PrivateConfig.EMPLOEE_CODE)){
            users = new ArrayList<>();
            users.add( loginUser);
        }else{
            //管理要能查看所有人的数据
            users = userAdminDao.findByBesideCodeOrderByJobNumberAsc( PrivateConfig.SUPER_ADMIN_CODE);
        }
        List<UserSummaryModel> summarys = new ArrayList<>();
        for( AdminUserTable user : users){
            if( "1".equals( user.getIdAgree())){
                continue;
            }
            //用户名下的卡
            /*
            MooncardCardModel mooncardCard = mooncardCardService.getFirstCard( user.getId());
            if( mooncardCard == null){
                //员工未设置mooncard卡，不返回他的数据
                continue;
            }*/
            UserSummaryModel summary = new UserSummaryModel();

            //1.员工工号
            String jobNumber = user.getJobNumber();
            //2.卡号
            //String cardNo = mooncardCard.getBankNo();
            //3.总充值（从注册以来，RECU页面中出现的所有充值收据，即包含支付宝扫码支付确定与
            //  未确定这两种状态与交易流水中手动充值已确认与未确认两种状态 的这两个充值内容）
            Double totalRecharge = Math.abs( rechargeRecordDao.sumByAdminUserId( user.getId()));
            //4.总消费（从注册以来，DEPENSE消费页面中出现的所有消费数据，包含MOONCARD消费与手动消费这两种消费内容）
            Double totalConsumer = Math.abs( consumerRecordDao.sumByImportUserId( user.getId()));
            //5.余额 总充值-总消费
            Double balance = totalRecharge - totalConsumer;
            //6.可用余额 余额减去支付宝充值未确定到账状态金额再减去手动充值未到账状态金额
            //         = 已到帐总充值金额 - 总消费
            Double validBalance = getValidBalance( user.getId());
            //7.前第三月充值 （前第三个月内的所有充值，即RECU页面中前第三个月的充值总额）
            //             查询前两个月
            Double threeRecharge = rechargeRecordDao.sumByAdminUserIdAndDealTimeFrench( user.getId(), DateFormatUtil.getLastNMonthZero( 3), DateFormatUtil.getLastNMonthZero( 2));
            //8.前第二月充值 同上
            Double towRecharge = rechargeRecordDao.sumByAdminUserIdAndDealTimeFrench( user.getId(), DateFormatUtil.getLastNMonthZero( 2), DateFormatUtil.getLastNMonthZero( 1));
            //9.前第一月前充值 同上
            Double oneRecharge = rechargeRecordDao.sumByAdminUserIdAndDealTimeFrench( user.getId(), DateFormatUtil.getLastNMonthZero( 1), DateFormatUtil.getLastNMonthZero( 0));
            //10.本月充值 这个地方和上面数据有点不同，需统计支付宝扫码支付,确定与未确定这两种状态与交易流水中手动充值,
            //   已确认与未确认两种状态 的这两个充值内容
            Double thisRecharge = rechargeRecordDao.sumByAdminUserIdAndDealTimeFrench( user.getId(), DateFormatUtil.getLastNMonthZero( 0), DateFormatUtil.format( new Date(), DateFormatUtil.DATE_RULE_3));
            //11.前第三月出口 审核通过的才算，以上传出口单的时间为时间段进行总金额统计
            Double threeExport = sendGoodsRecordDao.sumByAdminUserIdAndUploadCustomsClearanceFormTime( user.getId(), DateFormatUtil.getLastNMonthZero( 3), DateFormatUtil.getLastNMonthZero( 2));
            //12.前第二月出口 同上
            Double twoExport = sendGoodsRecordDao.sumByAdminUserIdAndUploadCustomsClearanceFormTime( user.getId(), DateFormatUtil.getLastNMonthZero( 2), DateFormatUtil.getLastNMonthZero( 1));
            //13.前第一月出口 同上
            Double oneExport = sendGoodsRecordDao.sumByAdminUserIdAndUploadCustomsClearanceFormTime( user.getId(), DateFormatUtil.getLastNMonthZero( 1), DateFormatUtil.getLastNMonthZero( 0));
            //14.本月出口 同上
            Double thisExport = sendGoodsRecordDao.sumByAdminUserIdAndUploadCustomsClearanceFormTime( user.getId(), DateFormatUtil.getLastNMonthZero( 0), DateFormatUtil.format( new Date(), DateFormatUtil.DATE_RULE_3));
            //15.昨天消费 在每天凌晨同步并核实MOONCARD 数据真实性后开始执行统计,就是整个一天出现在DEPENSE里面的消费情况，
            //   包含MOONCARD 消费 与  手动消费 这两个数据
            Double lastDayConsumer = getLastDayConsumer( user.getId());
            //16.30天内消费 在计算昨天消费后进行统计，包含统计当天，往前再推29天，也就是包含统计当天一共30天的消费情况，
            //   包含MOONCARD 消费 与  手动消费 这两个数据
            Double thirtyDayConsumer = getThirtyDayConsumer( user.getId());

            DecimalFormat df = new DecimalFormat("#.00");
            summary.setJobNumber( jobNumber);
            summary.setNom( user.getNom());
            summary.setIdAgree( user.getIdAgree());
            summary.setPrenom( user.getPrenom());
       //     summary.setCardNo( cardNo);
            summary.setBalance( df.format( balance));
            summary.setLastDayConsumer( df.format( lastDayConsumer));
            summary.setOneExport( df.format( oneExport));
            summary.setOneRecharge( df.format( oneRecharge));
            summary.setThirtyDayConsumer( df.format( thirtyDayConsumer));
            summary.setThisExport( df.format( thisExport));
            summary.setThisRecharge( df.format( thisRecharge));
            summary.setThreeExport( df.format( threeExport));
            summary.setThreeRecharge( df.format( threeRecharge));
            summary.setTotalConsumer( df.format( totalConsumer));
            summary.setTotalRecharge( df.format( totalRecharge));
            summary.setTowRecharge( df.format( towRecharge));
            summary.setTwoExport( df.format( twoExport));
            if( validBalance < 0){
                validBalance = 0.00;
            }
            summary.setValidBalance( df.format( validBalance));
            summarys.add( summary);
        }
        return summarys;
    }

    public Double getValidBalance( Long adminUserId){
        //总消费（从注册以来，DEPENSE消费页面中出现的所有消费数据，包含MOONCARD消费与手动消费这两种消费内容）
        Double totalConsumer = Math.abs( consumerRecordDao.sumByImportUserId( adminUserId));
        //已到帐总充值金额 - 总消费
        Double validBalance = rechargeRecordDao.sumByMoneyStatusAndAdminUserId( adminUserId) - totalConsumer;
        if( validBalance.equals( 0.00d) || validBalance < 0){
            validBalance = 0.00d;
        }
        return validBalance;
    }

    /**
     * 昨天消费 在每天凌晨同步并核实MOONCARD 数据真实性后开始执行统计,就是整个一天出现在DEPENSE里面的消费情况，
     *         包含MOONCARD 消费 与  手动消费 这两个数据
     * @param adminUserId
     * @return
     */
    public Double getLastDayConsumer( Long adminUserId){
        Double lastDayConsumer = consumerRecordDao.sumByImportUserIdAndTime( adminUserId, DateFormatUtil.getLastDayZeroForStr( 1), DateFormatUtil.getLastDayZeroForStr( 0));
        return Math.abs( lastDayConsumer);
    }

    /**
     * 30天内消费 在计算昨天消费后进行统计，包含统计当天，往前再推29天，也就是包含统计当天一共30天的消费情况，
     *          包含MOONCARD 消费 与  手动消费 这两个数据
     * @param adminUserId
     * @return
     */
    public Double getThirtyDayConsumer( Long adminUserId){
        Double thirtyDayConsumer = consumerRecordDao.sumByImportUserIdAndTime( adminUserId, DateFormatUtil.getLastDayZeroForStr( 29), DateFormatUtil.format( new Date(), DateFormatUtil.DATE_RULE_3));
        return Math.abs( thirtyDayConsumer);
    }
}
